const Service = require('egg').Service;
const fs = require('fs');
const path = require('path');
const regionJson = require('../utils/region.json');
const jobJson = require('../utils/job.json');
const qiniu = require('qiniu');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const md5 = require('md5');
const bucket = 'stacy-product'; //要上传的空间名
const imageUrl = 'http://cdn.lengnuanit.top/'; // 空间绑定的域名
const accessKey = 'on-BfV0xJsyd6na89jWMp50l4EdPPMfoZCu1bMmv';
const secretKey = '8sO6pUsPUKqCj72cS9dfa9p45qfzWgrbQD-p1l10';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
  scope: bucket,
  expires: 7200,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
let config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z0;
class BaseService extends Service {
  // 七牛云上传
  async upload() {
    const { ctx } = this;
    const stream = await ctx.getFileStream();
    const filename =
      md5(stream.filename) + path.extname(stream.filename).toLocaleLowerCase();
    const localFilePath = path.join(__dirname, '../public/uploads', filename);
    const writeStream = fs.createWriteStream(localFilePath);
    try {
      await awaitWriteStream(stream.pipe(writeStream));
      const formUploader = new qiniu.form_up.FormUploader(config);
      const putExtra = new qiniu.form_up.PutExtra();
      const imgSrc = await new Promise((resolve, reject) => {
        formUploader.putFile(
          uploadToken,
          filename,
          localFilePath,
          putExtra,
          (respErr, respBody, respInfo) => {
            if (respErr) {
              reject('');
            }
            if (respInfo.statusCode == 200) {
              resolve(imageUrl + respBody.key);
            } else {
              reject('');
            }
            // 上传之后删除本地文件
            fs.unlinkSync(localFilePath);
          }
        );
      });
      if (imgSrc !== '') {
        return {
          url: imgSrc,
        };
      } else {
        return false;
      }
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream);
      return false;
    }
  }
  // 七牛云上传凭证
  async token() {
    const { ctx } = this;
    return { token: uploadToken, prefix: imageUrl };
  }
  // 获取行政区域树形数据
  async tree() {
    try {
      return regionJson;
    } catch (error) {
      return null;
    }
  }

  // 获取职务数据
  async job() {
    try {
      return jobJson;
    } catch (error) {
      return null;
    }
  }

  // 获取所有省份城市
  async province() {
    try {
      const { ctx } = this;
      const result = await ctx.model.Region.findAll({
        where: {
          parentId: 0,
        },
      });
      return result;
    } catch (error) {
      return null;
    }
  }
  // 获取某个省份下面的所有城市
  async city({parentId}) {
    try {
      const { ctx } = this;
      const result = await ctx.model.Region.findAll({
        where: {
          parentId,
        },
      });
      return result;
    } catch (error) {
      return null;
    }
  }
}
module.exports = BaseService;
